package com.fish.config;

import com.fish.io.Resources;
import com.fish.pojo.Configuration;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

public class XMLConfigBuilder {

    private Configuration configuration;

    public XMLConfigBuilder() {
        this.configuration = new Configuration();
    }

    public Configuration parseConfig(InputStream inputStream) throws DocumentException, PropertyVetoException {

        Document document = new SAXReader().read(inputStream);

        //获取根节点
        Element rootElement = document.getRootElement();

        //封装DataSource属性
        parseDataSource(rootElement);

        //封装mappedSatement
        parseMappedStatement(rootElement);

        return configuration;
    }

    private void parseMappedStatement(Element rootElement) {

        //找到所有的mapper
        List<Element> list = rootElement.selectNodes("//mapper");

        //遍历list得到所有的mapper
        list.forEach(element -> {
            String mapperPath = element.attributeValue("resource");
            InputStream resourceAsSteam = Resources.getResourceAsStream(mapperPath);
            XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);
            try {
                xmlMapperBuilder.parse(resourceAsSteam);
            } catch (DocumentException e) {
                e.printStackTrace();
            }
        });
    }

    private void parseDataSource(Element rootElement) throws PropertyVetoException {

        //找到所有的property
        List<Element> list = rootElement.selectNodes("//property");
        Properties properties = new Properties();

        //遍历取得DataSource标签的所有属性值
        list.forEach(element ->{
            String name = element.attributeValue("name");
            String value = element.attributeValue("value");
            properties.setProperty(name,value);
        });

        //使用连接池封装DataSource属性
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
        comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        comboPooledDataSource.setUser(properties.getProperty("username"));
        comboPooledDataSource.setPassword(properties.getProperty("password"));

        //将DataSource封装进configuration
        configuration.setDataSource(comboPooledDataSource);
    }
}

